package com.example.pingapplication2.net;

import android.content.Context;
import android.util.Log;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 *亮点，使用观察者模式对多个页面进行通知
 */
public class RetrieveFeedTask {
    String TAG = "RetrieveFeedTask.class";

    private static RetrieveFeedTask INSTANCE;

    public List<INetListener> netListenerList = new ArrayList<>();

    public void registerListener(INetListener listener){
        netListenerList.add(listener);
    }

    //int curPingTimes = 0;//当前Ping的次数
    static Context mContext;


    private RetrieveFeedTask() {
    }

    public static RetrieveFeedTask getInstance(Context context){
        if(INSTANCE == null){
            synchronized (RetrieveFeedTask.class){
                if(INSTANCE == null){
                    INSTANCE = new RetrieveFeedTask();
                    mContext = context;
                }
            }
        }
        return INSTANCE;
    }

    public void pingThread(String[] urls, int count){
        //Log.d(TAG,"进入pingThread方法");
        Ping pingResult;//此为 ping 的结果
        double totalCount = 0;//ping 的总次数
        int passCount = 0;//ping 通的次数
        int failCount = 0;//ping 失败的总次数

        URL[] urlArray = new URL[2];
        try {
            urlArray[0]=new URL(urls[0]);
            urlArray[1]=new URL(urls[1]);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Log.d("ping","需要2个url,同时要是可取的url路径");
        }

        pingResult = Ping.ping(urlArray[count%2], mContext);
        if (pingResult.isSuccessful){
            Log.d(TAG, "ping 成功！");
            notifyPingSuccess();
        }else{
            Log.d(TAG, "ping 失败！");
            notifyPingFailure();
        }

        return;
    }

    private void notifyPingFailure() {
        for(INetListener listener:netListenerList){
            listener.pingFailure();
        }
    }

    private void notifyPingSuccess() {
        for(INetListener listener:netListenerList){
            listener.pingSuccess();
        }
    }

}
